<script setup>
/**
 * @name 文案库excel导入弹窗
 */
import { reactive, ref ,computed} from "vue";
import baseModel from "@/components/baseModel/baseModel.vue";
const dialog = ref()
import { InboxOutlined } from '@ant-design/icons-vue';
import { message } from "ant-design-vue";
import request from "@/common/utils/request";
import utils from "@/common/utils/utils";

const props = defineProps({
    // 文案库名称
    textLibrary: {
        type: Object,
        default: () => {
            return {
                name: '文案库名称',
                id:'123'
            }
        }
    },
    
})

const state = reactive({
    options: [],
    // 上传状态
    uploadStates:''
})

const formState = reactive({
    fileList: [],
    // 文案库 id
    textLibraryId:''
})

const filterOption = (input, option) => {
    // console.log(input, option, '什么东东');
    return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

// 文件上传change
const handleChange = (info) => {
    console.log(info,'结果?????');
    const status = info.file.status;
    // 赋值 状态
    if (status == 'done' || status == 'error') {
        state.uploadStates = ''
    } else {
        state.uploadStates = status
    }

    if (status !== 'uploading') {
        console.log(info.file, info.fileList);
    }
    if (status === 'done') {
        if (info.file?.response?.code != 1000) {
            formState.fileList = []
            return message.error('上传失败')
        }
        message.success(`上传成功! 请稍后刷新查看`);
        formState.fileList = []
        formState.textLibraryId = ''
        close()
    } else if (status === 'error') {
        message.error(`${info.file.name} 上传失败`);
        formState.fileList = []
    }
};

// 下载模板
const downLoadTemplate = async () => {
    const res = await  request.get(
      "/work_ai",
      "/user/import/demofile"
    );
    console.log(res, '下载地地址');
    if (res?.fileUrl) {
        const templateUrl = res?.fileUrl
            // 下载
        const response = await fetch(templateUrl); // 获取视频链接
        const blob = await response.blob(); // 将响应转为 Blob
        const url = window.URL.createObjectURL(blob); // 创建一个 blob URL
    
        const link = document.createElement("a");
        link.href = url; // 设置 href 为 blob URL
        link.download = "template.xlsx"; // 可选，设置下载时的文件名
        document.body.appendChild(link);
        link.click(); // 模拟点击下载
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url); // 清理
    }
}

const open = (params={}) => {
    const { textLibraryList = [], textLibraryId = '' } = params
    formState.textLibraryId = textLibraryId
    state.options = textLibraryList

    dialog.value?.showModal()
}

const curEnv=computed(()=>{
    return utils.isMobile()
      ? "h5"
      : import.meta.env.ELECTRON
      ? "desktop"
      : "pc";
})
const close = () => {
    dialog.value?.closeModal()
}
defineExpose({
    open,
    close
})

</script>

<template>
    <baseModel title="本地导入文案" ref="dialog" :maskClosable="false" :closable="false" :contentWidth="700">
        <template #content>
            <div class="content">
                <div class="title_box">
                    <div class="title_left">
                        <span>当前文案库:</span>
                        <a-select
                            v-model:value="formState.textLibraryId"
                            show-search
                            placeholder="请选择文案库"
                            style="width: 300px"
                            :options="state.options"
                            :filter-option="filterOption"
                            ></a-select>
                            <!-- @focus="handleFocus"
                            @blur="handleBlur"
                            @change="handleChange" -->

                    </div>
                    <div class="title_right">
                        <a-button type="link" @click="downLoadTemplate">下载模板</a-button>
                    </div>
                </div>

                <div class="content_main">
                    <div class="upload_box">
                        <a-upload-dragger
                        :disabled="state.uploadStates != ''"
                            v-model:fileList="formState.fileList"
                            name="file"
                            accept=".xlsx"
                            :data="{
                            dir: 'work_ai',
                                merchant_folder_statck_id: formState.textLibraryId,
                                user_token: $utils.getToken(),
                                org_id: $utils.getOrgId(),
                                team_id: $utils.getCurrentTeam(),
                                cur_env: curEnv
                             }"
                            :action="$utils.excelAction"
                            :maxCount="1"
                            :multiple="false"
                            @change="handleChange"
                            >
                            <!-- :data="{ dir: 'work_ai' }" -->
                            <!-- :action="$utils.fileAction" -->
                            <!-- @drop="handleDrop" -->
                            <p class="upload_icon">
                            <InboxOutlined />
                            </p>
                            <p class="upload_text">点击或将文件拖拽至此进行上传</p>
                            <p class="upload_hint">
                            仅支持上传 Excel 表格，暂不支持其他文件格式
                            </p>
                        </a-upload-dragger>
                    </div>
                </div>
            </div>
        </template>
        <template #footer>
            <!-- v-show="state.uploadStates != ''" -->
            <p class="bottom_p" v-show="state.uploadStates != ''">上传中，请勿刷新或关闭页面...</p>
            <a-button :loading="state.uploadStates != ''" @click="close">关闭</a-button>
        </template>
    </baseModel>
</template>

<style lang="less" scoped>

.content{

    
}
.title_box{
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    .title_left{
        span{
            margin-right: 10px;
        }
    }

}
.content_main{

    .upload_box{
        
        .upload_icon{
            font-size: 60px;
            color: rgb(33, 111, 255);
        }
        .upload_text{
            font-size: 16px;
            margin-bottom: 5px;
        }
        .upload_hint{
            font-size: 12px;
            color: #acacac;
        }
    }
}

.bottom_p{
    text-align: start;
    color: var(--ss-error-color);
    
}


</style>